package bbs.dao;

import java.util.List;
import java.util.Map;

import bbs.bean.Message;
import bbs.bean.User;
import bbs.util.DBHelper;

public class MessageDao {

	public void insert(Message msg) {
		String sql = "insert into message values(default,?,?,?,default,0)";
		DBHelper.update(sql, msg.getSendUid(), msg.getRecvUid(), msg.getContent());
	}

	public void update(String id) {
		String sql = "update message set readed = 1 where id = ?";
		DBHelper.update(sql, id);
	}

	/**
	 * 查询历史记录
	 * 查询方法  未完待续...
	 * @param sendUid
	 * @param RecvUid
	 * @return
	 */
	public List<Message> selectByRecvId(String  selfSend, String selfRecv,String otherSend,String otherRecv) {
		// TODO ..未完待续...
		String sql = "SELECT * FROM `message` where (send_uid=? or recv_uid=?)"
				+ " and (send_uid=? or recv_uid=?) ";
		return DBHelper.query(sql, Message.class, selfSend, selfRecv,otherSend,otherRecv);
	}
	/**
	 * 通过uid查找用户的头像和名字
	 * @param receiveUid
	 * @return
	 */
	public List<User> selectOther(String receiveUid){
		String sql = "select uname,ujpg from user where uid=?";
		return DBHelper.query(sql,User.class,receiveUid);
	}
	/**
	 * 查看当前用户的聊天列表信息
	 */
	public List<Map<String,Object>> selectList(String userSend,String userRecv){
		String sql = "select distinct m.recv_uid,u.uname,u.ujpg ,u.uid"
				+ " from message m LEFT JOIN user u on m.recv_uid=u.uid"
				+ " where m.recv_uid=? or m.send_uid= ?";
		List<Map<String,Object>>list = DBHelper.query(sql,userSend,userRecv);
		return list;
		
	}
	/**
	 * 查当前用户的未读消息的发送者id
	 */
	public List<Message>unread(String userRecv){
		String sql = "SELECT distinct send_uid ,recv_uid FROM `message`"
				+ " where recv_uid=?  and readed = 0 "
				+ " ORDER BY send_uid asc";
		List<Message>list = DBHelper.query(sql,Message.class,userRecv);
		return list;
		
	}
	/**
	 * 更新消息的读取状态
	 */
	public void changeread(String loginUid,String OtherUid){
		String sql = "update message set readed=1"
				+ " where (send_uid=? or recv_uid=?)"
				+ " and (send_uid=? or recv_uid=? )";
		 DBHelper.update(sql,loginUid,loginUid,OtherUid,OtherUid);
	}
}
